package com.example.demo.controller;

import com.example.demo.entity.Userinfo;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

import static org.springframework.transaction.annotation.Propagation.REQUIRED;

/**
 * @Author :蕉绿
 * @Date : 2023/3/9 19:15
 * @Version : V1.0
 * @Description :
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //JDBC的事务管理器
    @Autowired
    private DataSourceTransactionManager transactionManager;

    //定义事务属性
    @Autowired
    private TransactionDefinition transactionDefinition;

    @RequestMapping("/add")
    public int add(Userinfo userinfo) {

        //非空校验
        if( userinfo == null || !StringUtils.hasLength(userinfo.getUsername()) ) {
            return 0;
        }
        //1.开始事务
        TransactionStatus transactionStatus =
                transactionManager.getTransaction(transactionDefinition);

        //手动设置
        userinfo.setCreatetime(LocalDateTime.now());
        userinfo.setUpdatetime(LocalDateTime.now());


            int ret =  userService.add(userinfo);
        System.out.println("添加: " + ret);

        //2.回滚事务
        //transactionManager.rollback(transactionStatus);

        //3.提交事务
        transactionManager.commit(transactionStatus);
        return ret;
    }

    //@Transactional(isolation = Isolation.DEFAULT ) //声明式事务 自动提交
    @Transactional(propagation = REQUIRED)
    @RequestMapping("/insert")
    public int insert(Userinfo userinfo) {
        if(userinfo == null || !StringUtils.hasLength(userinfo.getUsername())) {
            return 0;

        }

        int ret = userService.add(userinfo);

        //捕捉到异常会commit
        try {
            int a= 10/0;
        } catch (Exception e) {
            //1.将异常继续抛出
//            throw e;
            e.printStackTrace();
        }

        //手动回滚

        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return ret;


    }
}
